package com.jiangyao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.jiangyao.common.ApiResult;
import com.jiangyao.common.exception.ServerException;
import com.jiangyao.common.utils.StringUtils;
import com.jiangyao.dao.ICategoryDao;
import com.jiangyao.model.dto.backend.CategoryDTO;
import com.jiangyao.model.dto.backend.CategoryListPageDTO;
import com.jiangyao.model.entity.Category;
import com.jiangyao.model.vo.backend.CategoryCountVO;
import com.jiangyao.service.CategoryService;
import org.dozer.DozerBeanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 分类信息 服务实现类
 * </p>
 *
 * @author zhoushuangxiang
 * @since 2020-08-12
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<ICategoryDao, Category> implements CategoryService {

	/**
	 * 数据分类对应的数据库表名
	 */
	private static final Map<Integer, String> TYPE_TABLE_NAME = Maps.newHashMapWithExpectedSize(4);

	static {
		// 1=课程
		TYPE_TABLE_NAME.put(1, "`subject`");
		// 课件
		TYPE_TABLE_NAME.put(2, "`courseware`");
		// 试题
		TYPE_TABLE_NAME.put(3, "`question`");
		// 职位
		TYPE_TABLE_NAME.put(4, "`job`");
	}

    @Autowired
    private ICategoryDao iCategoryDao;
    @Autowired
    private DozerBeanMapper dozerBeanMapper;


    @Override
    public List<Category> getJobCategory() {
        QueryWrapper<Category> queryWrapper = new QueryWrapper();
		queryWrapper.eq("type",4);
		queryWrapper.eq("status",1);
		queryWrapper.orderByDesc("sort_order");
	    return this.list(queryWrapper);
    }

	@Override
	public Page<Category> getListPage(CategoryListPageDTO listPageDTO) {
		QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
		if (listPageDTO.getType() != null && listPageDTO.getType() != -1) {
			queryWrapper.eq("type", listPageDTO.getType());
		}
		queryWrapper.eq("status", 1);
		queryWrapper.orderByDesc("id");
		Page<Category> page = new Page<>(listPageDTO.getPageNo(), listPageDTO.getPageSize());
		this.page(page, queryWrapper);
		return page;
	}

	@Override
	public void add(CategoryDTO categoryDTO) {
		Category category = getOneByTypeAndName(categoryDTO);
		if (category != null) {
			throw new ServerException(100, "分类名称已存在");
		}
		category = dozerBeanMapper.map(categoryDTO, Category.class);
		category.setId(null);
		category.setAddTime(new Date());
		this.save(category);
	}

	@Override
	public void edit(CategoryDTO categoryDTO) {
		Category categoryDB = this.getById(categoryDTO.getId());
		if (categoryDB == null || categoryDB.getStatus() != 1) {
			throw new ServerException(100, "分类不存在");
		}
		if (!categoryDB.getName().equals(categoryDTO.getName())) {
			categoryDTO.setType(categoryDB.getType());
			Category category = getOneByTypeAndName(categoryDTO);
			if (category != null) {
				throw new ServerException(100, "分类名称已存在");
			}
		}
		UpdateWrapper<Category> updateWrapper = new UpdateWrapper<>();
		updateWrapper.eq("id", categoryDTO.getId());
		updateWrapper.set("name", categoryDTO.getName());
		updateWrapper.set("sort_order", categoryDTO.getSortOrder());
		this.update(updateWrapper);
	}

	@Override
	public void del(CategoryDTO categoryDTO) {
		Category categoryDB = this.getById(categoryDTO.getId());
		if (categoryDB == null || categoryDB.getStatus() != 1) {
			throw new ServerException(100, "分类不存在");
		}
		// 检查分类是否删除
		checkDelete(categoryDB);
		// 删除
		UpdateWrapper<Category> updateWrapper = new UpdateWrapper<>();
		updateWrapper.eq("id", categoryDTO.getId());
		updateWrapper.set("status", 0);
		this.update(updateWrapper);

	}

	@Override
	public List<Category> listForSelect(CategoryDTO categoryDTO) {
		QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
		if (categoryDTO.getType() != null && categoryDTO.getType() != -1) {
			queryWrapper.eq("type", categoryDTO.getType());
		}
		queryWrapper.eq("status", 1);
		queryWrapper.orderByDesc("sort_order");
		return this.list(queryWrapper);
	}

	/**
	 * 根据类型、名称获取分类
	 *
	 * @param categoryDTO 组织名称
	 * @return 结果
	 */
	private Category getOneByTypeAndName(CategoryDTO categoryDTO) {
		if (StringUtils.isBlank(categoryDTO.getName())) {
			return null;
		}
		QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("type", categoryDTO.getType());
		queryWrapper.eq("name", categoryDTO.getName());
		queryWrapper.eq("status", 1);
		queryWrapper.last(" LIMIT 1");
		return this.getOne(queryWrapper);
	}

	/**
	 * 检查分类是否删除
	 *
	 * @param category 分类
	 */
	private void checkDelete(Category category) {
		Integer count = iCategoryDao.getUseCountForDel(category);
		if (count != null && count > 0) {
			throw new ServerException(100, "该分类还在使用中不能删除");
		}
	}

	@Override
	public List<CategoryCountVO> getCountList(CategoryDTO categoryDTO) {
		String tableName = TYPE_TABLE_NAME.get(categoryDTO.getType());
		if (StringUtils.isEmpty(tableName)) {
			return null;
		}
		return iCategoryDao.getCountList(categoryDTO.getType(), tableName);
	}
}
